package com.shilei.spring.collection;

import java.util.*;

/**
 * @author 石雷
 * shilei1@jiayuan.com
 * 2021/8/26/026 14:27
 *
 * 自定义带过期时间的HashSet
 *
 *  add时会检查过期元素进行删除
 *  遍历时请手动
 */
public class ExpireHashSet<T>{
    Map<T, Long>  expierMap = new HashMap<>();
    Set<T> datas = new HashSet<>();


    public int size() {
        return datas.size();
    }

    public boolean isEmpty() {
        return datas.isEmpty();
    }

    public boolean contains(Object o) {
        return datas.contains(o);
    }

    public Iterator iterator() {
        for (T data : datas) {

        }
        expierCheck();
        return datas.iterator();
    }


    public Object[] toArray() {
        return datas.toArray();
    }

    public boolean add(T o) {
        expierCheck();
        return datas.add(o);
    }

    public boolean add(T o,Long expier) {
        expierCheck();
        expierMap.put(o,System.currentTimeMillis()+expier);
        return datas.add(o);
    }

    public boolean remove(T o) {
        return datas.remove(o);
    }

    public boolean addAll(Collection c) {
        return false;
    }

    public void clear() {
       datas.clear();
       expierMap.clear();
    }

    public boolean removeAll(Collection<T> c) {
        for (T o : c) {
            expierMap.remove(o);
        }
        return datas.removeAll(c);
    }

    public boolean retainAll(Collection<T> c) {
        return datas.retainAll(c);
    }

    public boolean containsAll(Collection<T> c) {
        return datas.containsAll(c);
    }

    public T[] toArray(T[] a) {
        return datas.toArray(a);
    }

    private void expierCheck(){
        Iterator<Map.Entry<T, Long>> iterator = expierMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<T, Long> entry = iterator.next();
            System.out.println(System.currentTimeMillis()+"-"+entry.getValue());
            if(System.currentTimeMillis()>entry.getValue()){
                datas.remove(entry.getKey());
                iterator.remove();
            }
        }
    }
}
